<?php

namespace func;

class SqlServer
{
    private $link;

    /**
     * @return mixed
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * @param mixed $link
     */
    public function setLink($link)
    {
        $this->link = $link;
    }

    function __construct($config = array())
    {
        if(empty($config))
        {
            exit("请检查配置");
        }
		
        $host= isset($config['host']) ? $config['host'] : '';
        $database= isset($config['database']) ? $config['database'] : '';
        $user= isset($config['user']) ? $config['user'] : '';
        $pwd= isset($config['password']) ? $config['password'] : '';
        $conInfo=array('Database'=>$database,'UID'=>$user,'PWD'=>$pwd,'CharacterSet'=>'UTF-8');
        $link=sqlsrv_connect($host,$conInfo);
        if($link)
        {
            $this->setLink($link);
        }
        else
        {
            print_r( sqlsrv_errors(), true);
            if( ($errors = sqlsrv_errors() ) != null) {
                foreach( $errors as $error ) {
                    echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
                    echo "code: ".$error[ 'code']."<br />";
                    echo "message: ".mb_convert_encoding($error[ 'message'], "UTF-8", "GBK") ."<br />";
                }
            }
            die;
        }
    }

    function __destruct()
    {
        // TODO: Implement __destruct() method.
        unset($this->link);
    }

    function select($sql)
    {
        $data = sqlsrv_query($this->getLink(),$sql);
        if($data)
        {
            $result = [];
            while($row = sqlsrv_fetch_array( $data, SQLSRV_FETCH_ASSOC) ) {
                array_push($result,$row);
            }
            return $result;
        }
        else
        {
            die( print_r( sqlsrv_errors(), true));
        }
    }
}